package com.warmlight.voicepacket.ui.user;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.OSSRequest;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.umeng.analytics.MobclickAgent;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.base.BaseActivity;
import com.warmlight.voicepacket.data.eventbus.Login;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.http.ResponseData;
import com.warmlight.voicepacket.utils.GlideCornerTransform;
import com.warmlight.voicepacket.utils.GlideImageLoader;
import com.warmlight.voicepacket.utils.MobClickHelper;
import com.warmlight.voicepacket.utils.SPUtils;
import com.warmlight.voicepacket.utils.TimeFormatUtils;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.TreeMap;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

public class LoginEditUserInfoActivity extends BaseActivity implements View.OnClickListener {

    private ImageView iv_header;
    private EditText et_nickname;
    private LinearLayout ll_man;
    private ImageView iv_man;
    private TextView tv_man;
    private LinearLayout ll_woman;
    private ImageView iv_woman;
    private TextView tv_woman;
    private Button bt_save;
    private static final int IMAGE_PICKER = 10;
    private ImagePicker imagePicker;
    private int sex = 1;//1 男  2 女
    private String headerImg = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_edit_userinfo);
        initView();
        initlistener();
        initImagePicker();
        initAli();
    }

    private void initAli() {



//        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
//// 在移动端建议使用STS的方式初始化OSSClient，更多信息参考：[访问控制]
//        OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider("<StsToken.AccessKeyId>", "<StsToken.SecretKeyId>", "<StsToken.SecurityToken>");
//        ClientConfiguration conf = new ClientConfiguration();
//        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
//        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
//        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
//        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
//        OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider, conf);
    }

    private ProgressDialog progressDialog;
    //android.R.style.Theme_Material_Light_Dialog_Alert
    private void showProgressDialog(){
        if (progressDialog == null){
            progressDialog = new ProgressDialog(this,android.R.style.Theme_Material_Light_Dialog_Alert);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setMessage("图片上传中");
        }

        progressDialog.show();
    }

    private void hideProgressDialog(){
        if (progressDialog != null){
            if (progressDialog.isShowing()){
                progressDialog.dismiss();
            }
        }
    }

    public void asyncPutImage( String localFile) {
        RequestOptions options = new RequestOptions();
        options.transform(new GlideCornerTransform(getContext(),50));
        Glide.with(getContext()).asBitmap().load(localFile).apply(options).into(iv_header);

        String endpoint = HttpConfig.endpoint;
        String stsServer = "STS应用服务器地址，例如http://abc.com";
//推荐使用OSSAuthCredentialsProvider。token过期可以及时更新
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(HttpConfig.accessKeyId,HttpConfig.accessKeySecret);
//该配置类如果不设置，会有默认配置，具体可看该类
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求数，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSS mOss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
        final long upload_start = System.currentTimeMillis();
        final String object = HttpConfig.objectName()+"avator"+ TimeFormatUtils.getCurrentTimeMillis()+".png";
        if (object.equals("")) {
            Log.w("AsyncPutImage", "ObjectNull");
            return;
        }

        File file = new File(localFile);
        if (!file.exists()) {
            Log.w("AsyncPutImage", "FileNotExist");
            Log.w("LocalFile", localFile);
            return;
        }

        showProgressDialog();
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(HttpConfig.bucket, object, localFile);
        put.setCRC64(OSSRequest.CRC64Config.YES);
//        if (mCallbackAddress != null) {
//            // 传入对应的上传回调参数，这里默认使用OSS提供的公共测试回调服务器地址
//            put.setCallbackParam(new HashMap<String, String>() {
//                {
//                    put("callbackUrl", mCallbackAddress);
//                    //callbackBody可以自定义传入的信息
//                    put("callbackBody", "filename=${object}");
//                }
//            });
//        }

        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
                int progress = (int) (100 * currentSize / totalSize);
//                mDisplayer.updateProgress(progress);
//                mDisplayer.displayInfo("上传进度: " + String.valueOf(progress) + "%");

            }
        });

        OSSAsyncTask task = mOss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");

                Log.d("ETag", result.getETag());
                Log.d("RequestId", result.getRequestId());

                long upload_end = System.currentTimeMillis();
                OSSLog.logDebug("upload cost: " + (upload_end - upload_start) / 1000f);
//                mDisplayer.uploadComplete();
//                mDisplayer.displayInfo("Bucket: " + mBucket
//                        + "\nObject: " + request.getObjectKey()
//                        + "\nETag: " + result.getETag()
//                        + "\nRequestId: " + result.getRequestId()
//                        + "\nCallback: " + result.getServerCallbackReturnBody());
                headerImg = HttpConfig.ali + object;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        hideProgressDialog();
                        showToast("头像上传成功");
                    }
                });

            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                String info = "";
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                    info = clientExcepion.toString();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                    info = serviceException.toString();
                }
//                mDisplayer.uploadFail(info);
//                mDisplayer.displayInfo(info);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        hideProgressDialog();
                        showToast("头像上传失败，请重试");
                    }
                });

            }
        });
    }

    private void initImagePicker() {
        imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(false);  //显示拍照按钮
        imagePicker.setMultiMode(false);
        imagePicker.setCrop(true);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setSelectLimit(1);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
    }

    /**
     * 提交数据到后台
     */
    private void initData() {
        String nickname = et_nickname.getText().toString().trim();
        if (TextUtils.isEmpty(nickname)){
            showToast("请完善昵称");
            return;
        }
        if (TextUtils.isEmpty(headerImg)){
            showToast("请设置头像");
            return;
        }

        String url= HttpConfig.EDIT_PROFILE;
        TreeMap<String,String> map = new TreeMap<>();
        map.put("auth_key", SPUtils.getLoginAuthKey());
        map.put("avator",headerImg);
        map.put("nickname",nickname);
        map.put("sex",sex+"");
        HttpClient.getInstance().postRxAndroidAES(url,map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseData>() {
                    @Override
                    public void accept(ResponseData responseData) throws Exception {
                        if (TextUtils.equals("200",responseData.getCode())){
//                            showToast("登录成功");
                            EventBus.getDefault().post(new Login(true));
                            finish();
//                            loginSuccess();
                        }else{
                            showToast(responseData.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        showToast("网络连接失败，请重试");
                    }
                });

    }

    private void initlistener() {
        iv_header.setOnClickListener(this);
        ll_man.setOnClickListener(this);
        ll_woman.setOnClickListener(this);
        bt_save.setOnClickListener(this);
        et_nickname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //埋点
                MobclickAgent.onEvent(getContext(), MobClickHelper.USERINFO_NAME);
//                HashMap<String, Object> temp = new HashMap<>();
//                temp.put("登录返回", "");
                ZhugeSDK.getInstance().track(getContext(), MobClickHelper.USERINFO_NAME);
            }
        });
    }

    private void initView() {
        setTitle("完善个人资料");
        setBack();
        setBackShow(true);
        iv_header = (ImageView) findViewById(R.id.iv_header);
        et_nickname = (EditText) findViewById(R.id.et_nickname);
        ll_man = (LinearLayout) findViewById(R.id.ll_man);
        iv_man = (ImageView) findViewById(R.id.iv_man);
        tv_man = (TextView) findViewById(R.id.tv_man);
        ll_woman = (LinearLayout) findViewById(R.id.ll_woman);
        iv_woman = (ImageView) findViewById(R.id.iv_woman);
        tv_woman = (TextView) findViewById(R.id.tv_woman);
        bt_save = (Button) findViewById(R.id.bt_save);

        ll_woman.setSelected(false);
        ll_man.setSelected(true);
        iv_man.setImageResource(R.drawable.icon_sex_man_n);
        tv_man.setTextColor(getResources().getColor(R.color.color_white));
        iv_woman.setImageResource(R.drawable.icon_sex_woman_y);
        tv_woman.setTextColor(getResources().getColor(R.color.color_666));
        sex = 1;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_header:
                //埋点
                MobclickAgent.onEvent(getContext(), MobClickHelper.USERINFO_AVATAR);
//                HashMap<String, Object> temp = new HashMap<>();
//                temp.put("登录返回", "");
                ZhugeSDK.getInstance().track(getContext(), MobClickHelper.USERINFO_AVATAR);
                Intent intent = new Intent(getContext(), ImageGridActivity.class);
                startActivityForResult(intent, IMAGE_PICKER);
                break;
            case R.id.ll_man:
                //埋点
                MobclickAgent.onEvent(getContext(), MobClickHelper.USERINFO_SEX);
//                HashMap<String, Object> temp = new HashMap<>();
//                temp.put("登录返回", "");
                ZhugeSDK.getInstance().track(getContext(), MobClickHelper.USERINFO_SEX);
                ll_woman.setSelected(false);
                ll_man.setSelected(true);
                iv_man.setImageResource(R.drawable.icon_sex_man_n);
                tv_man.setTextColor(getResources().getColor(R.color.color_white));
                iv_woman.setImageResource(R.drawable.icon_sex_woman_y);
                tv_woman.setTextColor(getResources().getColor(R.color.color_666));
                sex = 1;
                break;
            case R.id.ll_woman:
                //埋点
                MobclickAgent.onEvent(getContext(), MobClickHelper.USERINFO_SEX);
//                HashMap<String, Object> temp = new HashMap<>();
//                temp.put("登录返回", "");
                ZhugeSDK.getInstance().track(getContext(), MobClickHelper.USERINFO_SEX);
                ll_woman.setSelected(true);
                ll_man.setSelected(false);
                iv_man.setImageResource(R.drawable.icon_sex_man_y);
                tv_man.setTextColor(getResources().getColor(R.color.color_666));
                iv_woman.setImageResource(R.drawable.icon_sex_woman_n);
                tv_woman.setTextColor(getResources().getColor(R.color.color_white));
                sex = 2;
                break;
            case R.id.bt_save:
                //埋点
                MobclickAgent.onEvent(getContext(), MobClickHelper.USERINFO_YES);
//                HashMap<String, Object> temp = new HashMap<>();
//                temp.put("登录返回", "");
                ZhugeSDK.getInstance().track(getContext(), MobClickHelper.USERINFO_YES);
                initData();
                break;
        }
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null && images.size()>0) {
                    asyncPutImage(images.get(0).path);
                }
            } else {
                showToast("没有数据");
            }
        }
    }



}
